package pro.cherish.knowledgeruntime.web.session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import pro.cherish.knowledgecmomon.entity.BaseException;
import pro.cherish.knowledgeruntime.constant.RuntimeConstant;
import pro.cherish.knowledgeutil.json.JsonUtilExt;

import java.util.concurrent.TimeUnit;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2019-11-03 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：RedisSessionServiceImpl
 * @Description 功能说明：redis实现session会话存储
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2019-11-03 cherish
 */
@Component
public class RedisSessionServiceImpl implements ISessionService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Value("${common.session.timeout}")
    private Integer timeout;

    @Override
    public void set(CommonSession commonSession) throws BaseException {
        this.set(commonSession.getSid(), commonSession, timeout, TimeUnit.SECONDS);
    }

    @Override
    public CommonSession get(String token) throws BaseException {
        String key = getTokenKey(token);
        return JsonUtilExt.fromJson(redisTemplate.boundValueOps(key).get(), CommonSession.class);
    }

    @Override
    public void remove(String token) throws BaseException {
        redisTemplate.delete(getTokenKey(token));
    }

    @Override
    public void set(String token, Object session, long c, TimeUnit timeUnit) throws BaseException {
        redisTemplate.opsForValue().set(getTokenKey(token), JsonUtilExt.toJsonString(session), timeout, timeUnit);
    }

    @Override
    public <T> T get(String token, Class<T> clazz) throws BaseException {
        String key = getTokenKey(token);
        return JsonUtilExt.fromJson(redisTemplate.boundValueOps(key).get(), clazz);
    }

    private String getTokenKey(String token) {
        return RuntimeConstant.SESSION_TOKEN_PREFIX + token;
    }
}
